const express = require('express');
const router = express.Router();
const Device = require('../../models/Device');
const auth = require('../../middleware/auth');

// 获取设备列表
router.get('/', auth, async (req, res) => {
  try {
    const { page = 1, limit = 10, type, status, location } = req.query;
    
    // 构建查询条件
    const query = {};
    if (type) query.type = type;
    if (status) query.status = status;
    if (location) query.location = new RegExp(location, 'i');

    const devices = await Device.find(query)
      .limit(limit * 1)
      .skip((page - 1) * limit)
      .sort({ createdAt: -1 });

    const total = await Device.countDocuments(query);

    res.json({
      success: true,
      data: devices,
      pagination: {
        current: parseInt(page),
        pageSize: parseInt(limit),
        total,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取设备列表错误:', error);
    res.status(500).json({
      success: false,
      error: '获取设备列表失败'
    });
  }
});

// 获取设备统计
router.get('/stats/summary', auth, async (req, res) => {
  try {
    const total = await Device.countDocuments();
    const online = await Device.countDocuments({ status: 'online' });
    const offline = await Device.countDocuments({ status: 'offline' });
    const warning = await Device.countDocuments({ status: 'error' });
    const maintenance = await Device.countDocuments({ status: 'maintenance' });
    
    const onlineRate = total > 0 ? ((online / total) * 100).toFixed(1) : '0';

    // 按类型统计
    const typeStats = await Device.aggregate([
      {
        $group: {
          _id: '$type',
          count: { $sum: 1 },
          online: {
            $sum: {
              $cond: [{ $eq: ['$status', 'online'] }, 1, 0]
            }
          }
        }
      }
    ]);

    res.json({
      success: true,
      data: {
        total,
        online,
        offline,
        warning,
        maintenance,
        onlineRate,
        typeStats: typeStats.reduce((acc, item) => {
          acc[item._id] = item;
          return acc;
        }, {})
      }
    });
  } catch (error) {
    console.error('获取设备统计错误:', error);
    res.status(500).json({
      success: false,
      error: '获取设备统计失败'
    });
  }
});

// 获取单个设备
router.get('/:id', auth, async (req, res) => {
  try {
    const device = await Device.findById(req.params.id);
    if (!device) {
      return res.status(404).json({
        success: false,
        error: '设备不存在'
      });
    }
    res.json({
      success: true,
      data: device
    });
  } catch (error) {
    console.error('获取设备详情错误:', error);
    res.status(500).json({
      success: false,
      error: '获取设备详情失败'
    });
  }
});

// 创建设备
router.post('/', auth, async (req, res) => {
  try {
    const device = new Device({
      ...req.body,
      createdBy: req.user._id
    });
    
    await device.save();
    
    res.status(201).json({
      success: true,
      message: '设备创建成功',
      data: device
    });
  } catch (error) {
    console.error('创建设备错误:', error);
    if (error.code === 11000) {
      res.status(400).json({
        success: false,
        error: '设备IP地址已存在'
      });
    } else {
      res.status(500).json({
        success: false,
        error: '创建设备失败'
      });
    }
  }
});

// 更新设备
router.put('/:id', auth, async (req, res) => {
  try {
    const device = await Device.findByIdAndUpdate(
      req.params.id,
      { ...req.body, updatedAt: new Date() },
      { new: true, runValidators: true }
    );
    
    if (!device) {
      return res.status(404).json({
        success: false,
        error: '设备不存在'
      });
    }
    
    res.json({
      success: true,
      message: '设备更新成功',
      data: device
    });
  } catch (error) {
    console.error('更新设备错误:', error);
    res.status(500).json({
      success: false,
      error: '更新设备失败'
    });
  }
});

// 删除设备
router.delete('/:id', auth, async (req, res) => {
  try {
    const device = await Device.findByIdAndDelete(req.params.id);
    
    if (!device) {
      return res.status(404).json({
        success: false,
        error: '设备不存在'
      });
    }
    
    res.json({
      success: true,
      message: '设备删除成功'
    });
  } catch (error) {
    console.error('删除设备错误:', error);
    res.status(500).json({
      success: false,
      error: '删除设备失败'
    });
  }
});

// 设备控制
router.post('/:id/control', auth, async (req, res) => {
  try {
    const { action } = req.body;
    const device = await Device.findById(req.params.id);
    
    if (!device) {
      return res.status(404).json({
        success: false,
        error: '设备不存在'
      });
    }

    // 根据操作更新设备状态
    let newStatus = device.status;
    let message = '';

    switch (action) {
      case 'startup':
        newStatus = 'online';
        message = '设备启动成功';
        break;
      case 'shutdown':
        newStatus = 'offline';
        message = '设备关闭成功';
        break;
      case 'restart':
        newStatus = 'online';
        message = '设备重启成功';
        break;
      case 'maintenance':
        newStatus = device.status === 'maintenance' ? 'offline' : 'maintenance';
        message = newStatus === 'maintenance' ? '设备进入维护模式' : '设备退出维护模式';
        break;
      case 'reset':
        newStatus = 'offline';
        message = '设备重置成功';
        break;
      case 'update':
        message = '设备更新成功';
        break;
      default:
        return res.status(400).json({
          success: false,
          error: '无效的操作'
        });
    }

    // 更新设备状态
    device.status = newStatus;
    device.lastHeartbeat = new Date();
    await device.save();

    res.json({
      success: true,
      message,
      data: device
    });
  } catch (error) {
    console.error('设备控制错误:', error);
    res.status(500).json({
      success: false,
      error: '设备控制失败'
    });
  }
});

module.exports = router;
